<?php

class MessageController extends Zend_Controller_Action
{

	protected $_session;
	
    public function init()
    {
    	//read the session.
        $storage = new Zend_Auth_Storage_Session();
		$session = $storage->read();
		//there is no data in session, then direct to login action
		if(!$session){
			$this->_redirect('auth/login');
		}
		//there is data in session, show the user's information
		$this->_session = $session;
    }

    public function indexAction()
    {
        // action body
    }

    public function meAction(){
    	
    	//get user id from session.
    	$uid = $this->_session->user_id;
    	$token = $this->_session->fb_account;
        $mModel = new Model_MessagesMapper();
        $friendMapper = new Model_FriendsMapper();
        $venueMapper = new Model_VenuesMapper();
        $venue = new Model_Venues();
        
        //call face to get the like infomation
        $url = 'https://graph.facebook.com/me/likes?access_token='.$token;
        
        //connect face book with curl which recommand by face book.
    	$ch = curl_init();
    	$options = array(
			CURLOPT_URL => $url,
			CURLOPT_HEADER => false,
			CURLOPT_SSL_VERIFYPEER => false,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_RETURNTRANSFER => true
		);
    	curl_setopt_array($ch, $options);
		$data = curl_exec($ch);
		curl_close($ch);
		
		//$urlPlaces = 'https://graph.facebook.com/me/checkins?access_token='.$token;
		//as the url upon, we could get the check in information and the lat and lon of the places.
		//however it is hard to combind it to our venue. So at this time, we just put the 
		//user to HKU venue by default
		$venueId = 1;
        
        //send the session to view.
        $this->view->profile = $this->_session;
        //send the venue and its message to view.
        $this->view->friends = $friendMapper->findFriendsListByUserid($uid);
        $this->view->messages = $mModel->findMessageByVenueId($venueId);
        $venueMapper->find($venueId, $venue);
        $this->view->venue = $venue;
        //send the like info from face book to view.
        $this->view->like = $data;
    }
    
    public function getmessagebyajaxAction(){
    	
    	$venueId = $_REQUEST['venue_id'];
    	$messageMapper = new Model_MessagesMapper();
    	$messages = $messageMapper->findMessageByVenueId($venueId);
    	$r = array();
    	foreach ($messages as $message){
    		$t=array (
    			'message_id' => $message->getMessage_id(),
                'message_content' => $message->getMessage_content(),
	        	'venue_id' => $message->getVenue_id(),
	    		'venue_name' => $message->getVenue_name(),
	        	'user_id' => $message->getUser_id(),
	    		'user_name' => $message->getUser_name(),
	        	'public_time' => $message->getPublic_time(),
	    		'reply' => $message->getReply()
            );
            $r[]=$t;
    	}
    	//return view with json.
        $this->_helper->json($r);
    }
    
	public function getmessagesAction(){
		
		//get venue id from view.
		$venueId = $_REQUEST['venue_id'];
		$messageMapper = new Model_MessagesMapper();
		$venueMapper = new Model_VenuesMapper();
		$venue = new Model_Venues();
//               var_dump($venue);die;
		//get messages of the venue.
                $venueMapper->find($venueId, $venue);
//                var_dump($venue);die;
		$messages = $messageMapper->findMessageByVenueId($venueId);
		$childrenVenues = $venueMapper->findChildrenInfo($venueId);
		//send session to view.
		$this->view->session = $this->_session;
		//send venue to view.
		$this->view->venue = $venue;
		$this->view->childrenVenues = $childrenVenues;
		//send the messages to view.

		$this->view->message = $messages;
                 
	}

	public function postmessageAction(){
		
		//get user id and name from session.
		$session = $this->_session;
		$userId = $session->user_id;
		$userName = $session->name;
		
		$messageMapper = new Model_MessagesMapper();
		$message = new Model_Messages();
		
		//get the message content from view.
		$messageContent = $_REQUEST['message_content'];
		$venueId = $_REQUEST['venue_id'];
		$venueName = $_REQUEST['venue_name'];
		$messageId = $_REQUEST['message_id'];
		
		//the message must belong to a venue, so it should be a venue id. If not, return.
		if(empty($venueId)){
			$this->_helper->json(array("result"=>"The venue has not been registered. Please try again or select one."));
			return;
		}
		$reply = 0;//it means the message is not a reply. it is the default number.
		
		//if the message id is existed, it means the message is a reply of the message with the provided id.
		if($messageId){
			$reply = $messageId;
		}
		
		//set the value to message and update.
		$message->setMessage_content($messageContent);
		$message->setPublic_time(date('Y-m-d H:i:s'));
		$message->setReply($reply);
		$message->setUser_id($userId);
		$message->setUser_name($userName);
		$message->setVenue_id($venueId);
		$message->setVenue_name($venueName);
		
		//update the database.
		try{
			$messageMapper->saveMessage($message);
			$this->_helper->json(array("result"=>"The message has been post"));
		} catch (Exception $e){
			$this->_helper->json(array("result"=>"The message was post failed"));
		}
	}
	
	public function editAction(){
		
		//get the session and message data which should be updated
		$session = $this->_session;
		$messageId = $_REQUEST['message_id'];
		$messageContent = $_REQUEST['message_content'];
		
		//if it could not get the message id, return.
		if(!$messageId){
			$this->view->errorMessage = "No message id";
			return;
		}
		
		$message = new Model_Messages();
		$messageMapper = new Model_MessagesMapper();
		
		$messageMapper->find($messageId, $message);
		//if it could not find the message of the id, return.
		if(!$message){
			$this->view->errorMessage = "can not find the message";
			return;
		}
		
		//if the message is not post by the user and the user is not admin role user. it could not be modified.
		if($session->user_id != $message->getUser_id() && 2 != $session->user_type){
			$this->view->errorMessage = "you can not modify others";
			return;
		}
		
		//update the message.
		$message->setMessage_id($messageId);
		$message->setMessage_content($messageContent);
		$message->setPublic_time(date('Y-m-d H:i:s'));
		
		$messageMapper -> saveMessage($message);
	}
	
	public function delAction(){
		
		//get session and message id.
		$session = $this->_session;
		$messageId = $_REQUEST['message_id'];
		
		//if it could not get the message id, return.
		if(!$messageId){
			$this->view->errorMessage = "No message id";
			return;
		}
		
		$message = new Model_Messages();
		$messageMapper = new Model_MessagesMapper();
		$messageDB = new Model_DbTable_Messages();
		
		$messageMapper->find($messageId, $message);
		//if it could not find the message of the id, return.
		if(!$message){
			$this->view->errorMessage = "can not find the message";
			return;
		}
		
		//if the message is not post by the user and the user is not admin role user. it could not be deleted.
		if($session->user_id != $message->getUser_id() && 2 != $session->user_type){
			$this->view->errorMessage = "you can not delete others";
			return;
		}
		//delete the message from database.		
		$messageDB->delete(array('message_id=?'=>$messageId));
	}
}

